package com.bhp.security.config;

import com.bhp.security.entity.Menu;
import com.bhp.security.entity.Role;
import com.bhp.security.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * @ClassName BhpFilterInvocationSecurityMetadataSource
 * @Description 自定义资源拦截器：用于动态配置权限
 * @Author 包海鹏
 * @Date 2020/4/11 15:53
 * @Version 1.0
 **/
@Component
public class BhpFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private MenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    // 获取当前访问的URL所需的角色
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {

        String url = ((FilterInvocation) o).getRequestUrl();
        List<Menu> menuList = menuService.getList();
        for (Menu menu : menuList) {
            if (antPathMatcher.match(menu.getPattren(),url)){
                List<Role> roles = menu.getRoles();
                return SecurityConfig.createList(roles.toArray(new String[roles.size()]));
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    // 返回所有定义好的资源，启动时会进行校验，不需要校验直接返回null
    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {

        return null;
    }

    // 类对象是否支持校验
    @Override
    public boolean supports(Class<?> aClass) {

        return true;
    }
}
